package cc.magicjson.example.demo.ali;

import java.util.Arrays;
import java.util.Random;

// 定义Door接口，表示一扇门及其状态
interface Door {
    boolean hasCar(); // 判断门后面是否有奖品（汽车）
}

// 实现Door接口的具体门类
class RealDoor implements Door {
    private boolean hasCar;

    public RealDoor(boolean hasCar) {
        this.hasCar = hasCar;
    }

    @Override
    public boolean hasCar() {
        return hasCar;
    }
}

// 游戏逻辑处理类
class GameSession {
    private final Door[] doors;
    private final Random random;

    public GameSession(Door[] doors) {
        this.doors = doors;
        this.random = new Random();
    }

    // 模拟游戏流程
    public Door playGameWithSwitch() {
        // 随机选择一扇门
        Door initialChoice = doors[random.nextInt(doors.length)];

        // 找到并打开一扇没有奖品的门（假设主持人知道每扇门后面的内容）
        Door openedDoor = Arrays.stream(doors)
                .filter(door -> !door.hasCar() && door != initialChoice)
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("No suitable door to open")); // 此处应永远不会发生

        // 剩下的门即为改选的目标门
        Door finalChoice = Arrays.stream(doors)
                .filter(door -> door != initialChoice && door != openedDoor)
                .findFirst()
                .orElseThrow(() -> new IllegalStateException("Invalid state - no other door available"));

        return finalChoice;
    }
}

public class MontyHallProblemSimulatorByAli {

    public static void main(String[] args) {
        // 创建三扇门，一扇有奖品
        Door door1 = new RealDoor(false);
        Door door2 = new RealDoor(true); // 假设第二扇门有奖品
        Door door3 = new RealDoor(false);
        Door[] doors = {door1, door2, door3};

        // 进行大量模拟实验
        int totalGames = 1000000;
        int winsBySwitching = 0;
        GameSession session = new GameSession(doors);

        for (int i = 0; i < totalGames; i++) {
            Door winningDoor = session.playGameWithSwitch();
            if (winningDoor.hasCar()) {
                winsBySwitching++;
            }
        }

        double winPercentage = (double) winsBySwitching / totalGames * 100;
        System.out.printf("通过改变选择赢得奖品的概率是: %.2f%%", winPercentage);
    }
}